package com.hp.gxw.utils;

import cn.hutool.core.date.DateUnit;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hp.gxw.entity.*;
import com.hp.gxw.service.ICustomerService;
import com.hp.gxw.service.IMesApiFailRecordService;
import com.hp.gxw.service.IProductService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.*;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Component
@Slf4j
public class HttpRequestUtils {

	@Autowired
	private IMesApiFailRecordService iMesApiFailRecordService;

	@Value("${mesapi.productData}")
	private String productDataUrl;

	@Value("${mesapi.workStatusData}")
	private String workStatusData;

	@Autowired
	private IProductService iProductService;

	@Autowired
	private ICustomerService iCustomerService;

	public void request(String uploadUrl, Map<String, Object> param, String type, String method) {
		/** 网络的url地址 */
		URL url = null;
		HttpURLConnection httpUrlConnection = null ;
		DataOutputStream  out = null; //写
		InputStream inputStream = null; //读
		BufferedReader in = null;
		String result = null;
		MesApiFailRecord mesApiFailRecord = iMesApiFailRecordService.getOne(new LambdaQueryWrapper<MesApiFailRecord>()
				.eq(MesApiFailRecord::getType,type).eq(MesApiFailRecord::getParam,JSON.toJSONString(param)));
		if(mesApiFailRecord == null){
			mesApiFailRecord = new MesApiFailRecord();
		}
		try {
			url = new URL(uploadUrl);
			httpUrlConnection = (HttpURLConnection) url.openConnection();
			httpUrlConnection.setConnectTimeout(5000);
			httpUrlConnection.setReadTimeout(5000);
			httpUrlConnection.setRequestMethod(method);
			// Post 请求不能使用缓存
			httpUrlConnection.setUseCaches(false);
			httpUrlConnection.setRequestProperty("Content-Type","application/json;charset=UTF-8");
			//传入参数
			httpUrlConnection.setDoOutput(true);
			out = new DataOutputStream(httpUrlConnection.getOutputStream());
			out.writeBytes(JSON.toJSONString(param));
//			out.write(param.getBytes("UTF-8"));
			out.flush();
			out.close();
			inputStream = httpUrlConnection.getInputStream();

			in = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
			String res;
			while ((res = in.readLine()) != null) {
				result = res;
			}
			Map map = JSON.parseObject(result, Map.class);
			if(map == null) {
				log.error("【"+type+"】返回结果:接口没有任何信息返回");
				mesApiFailRecord.setType(type);
				mesApiFailRecord.setParam(JSON.toJSONString(param));
				mesApiFailRecord.setResultCode(null);
				mesApiFailRecord.setResultMsg("接口没有任何信息返回");
				mesApiFailRecord.setUpdateTime(new Date());
			}
			if(!"200".equals(map.get("code").toString())) {
				log.error("【"+type+"】返回结果:"+map.get("code")+"-"+map.get("msg"));
				mesApiFailRecord.setType(type);
				mesApiFailRecord.setParam(JSON.toJSONString(param));
				mesApiFailRecord.setResultCode(map.get("code").toString());
				mesApiFailRecord.setResultMsg(map.get("msg").toString());
				mesApiFailRecord.setUpdateTime(new Date());
			}
		} catch (Exception e) {
			log.error("【"+type+"】返回结果:Http请求过程中发生了异常，message："+e.getMessage());
			mesApiFailRecord.setType(type);
			mesApiFailRecord.setParam(JSON.toJSONString(param));
			mesApiFailRecord.setResultCode(null);
			mesApiFailRecord.setResultMsg("Http请求过程中发生了异常");
			mesApiFailRecord.setUpdateTime(new Date());
			e.printStackTrace();
		}finally {
			try {
				in.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			httpUrlConnection.disconnect();
		}
		iMesApiFailRecordService.saveOrUpdate(mesApiFailRecord);
	}

	public List<CostProductData> requestProductData(String date) {
		/** 网络的url地址 */
		URL url = null;
		HttpURLConnection httpUrlConnection = null ;
		DataOutputStream  out = null; //写
		InputStream inputStream = null; //读
		BufferedReader in = null;
		List<CostProductData> costProductDataList = new ArrayList<>();
		try {
			url = new URL(productDataUrl+"?date="+date);
			httpUrlConnection = (HttpURLConnection) url.openConnection();
			httpUrlConnection.setConnectTimeout(5000);
			httpUrlConnection.setReadTimeout(5000);
			httpUrlConnection.setRequestMethod("GET");
			// Post 请求不能使用缓存
			httpUrlConnection.setUseCaches(false);
			httpUrlConnection.setRequestProperty("Content-Type","application/json");
			inputStream = httpUrlConnection.getInputStream();
			in = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
			String res;
			String result = null;
			while ((res = in.readLine()) != null) {
				result = res;
			}
			if(result != null){
				List<Map> mapList = JSON.parseArray(result, Map.class);
				for (Map map : mapList) {
					CostProductData costProductData = new CostProductData();
					costProductData.setProcessCode(map.get("group_id")==null?"":map.get("group_id").toString());
					costProductData.setProcessName(map.get("group_name")==null?"":map.get("group_name").toString());
					costProductData.setWorkOrder(map.get("mo_no")==null?"":map.get("mo_no").toString());
					costProductData.setSaleOrder(map.get("inner_order_code")==null?"":map.get("inner_order_code").toString());
					costProductData.setCinvcode(map.get("key_part_no")==null?"":map.get("key_part_no").toString());
					if(map.get("key_part_no")!=null){
						Product product = iProductService.getOne(new LambdaQueryWrapper<Product>().eq(Product::getCode, map.get("key_part_no").toString()));
						if(product != null){
							costProductData.setCinvname(product.getName());
						}
					}
					costProductData.setQty(map.get("target_qty")==null? BigDecimal.ZERO:new BigDecimal(map.get("target_qty").toString()));
					costProductData.setCustomerCode(map.get("cust_code")==null?"":map.get("cust_code").toString());
					if(map.get("cust_code")!=null){
						Customer customer = iCustomerService.getOne(new LambdaQueryWrapper<Customer>().eq(Customer::getCode, map.get("cust_code").toString()));
						if(customer != null){
							costProductData.setCustomerName(customer.getName());
						}
					}
					costProductData.setStartTime(map.get("in_station_time")==null?null:DateUtil.getDateTimeSlashFormat(map.get("in_station_time").toString()));
					costProductData.setEndTime(map.get("out_station_time")==null?null:DateUtil.getDateTimeSlashFormat(map.get("out_station_time").toString()));
					if(map.get("in_station_time")!=null && map.get("out_station_time")!=null){
						BigDecimal seconds = DateUtil.between(costProductData.getStartTime(), costProductData.getEndTime(), DateUnit.SECOND);
						costProductData.setWorkingHours(seconds.divide(new BigDecimal(3600),BigDecimal.ROUND_HALF_UP,4));
					}
					List<Map> details = JSON.parseArray(map.get("details").toString(),Map.class);
					List<CostProcessEquipment> processEquipmentList = new ArrayList<>();
					for (Map detail : details) {
						CostProcessEquipment costProcessEquipment = new CostProcessEquipment();
						costProcessEquipment.setProcessCode(costProductData.getProcessCode());
						costProcessEquipment.setWorkOrder(costProductData.getWorkOrder());
						costProcessEquipment.setEquipmentCode(detail.get("machine_code")==null?"":detail.get("machine_code").toString());
						costProcessEquipment.setMonth(date.substring(0,7));
						processEquipmentList.add(costProcessEquipment);
					}
					costProductData.setProcessEquipmentList(processEquipmentList);
					costProductData.setMonth(date.substring(0,7));
					costProductDataList.add(costProductData);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}finally {
			try {
				in.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			httpUrlConnection.disconnect();
		}
		return costProductDataList;
	}

	public List<CostWorkOrderStatus> requestWorkOrderStatus(String startDate, String endDate) {
		/** 网络的url地址 */
		URL url = null;
		HttpURLConnection httpUrlConnection = null ;
		DataOutputStream  out = null; //写
		InputStream inputStream = null; //读
		BufferedReader in = null;
		List<CostWorkOrderStatus> costWorkOrderStatusList = new ArrayList<>();
		try {
			url = new URL(workStatusData+"?date1="+startDate+"&date2="+endDate);
			httpUrlConnection = (HttpURLConnection) url.openConnection();
			httpUrlConnection.setConnectTimeout(5000);
			httpUrlConnection.setReadTimeout(5000);
			httpUrlConnection.setRequestMethod("GET");
			// Post 请求不能使用缓存
			httpUrlConnection.setUseCaches(false);
			httpUrlConnection.setRequestProperty("Content-Type","application/json");
			inputStream = httpUrlConnection.getInputStream();
			in = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
			String res;
			String result = null;
			while ((res = in.readLine()) != null) {
				result = res;
			}
			List<Map> mapList = JSON.parseArray(result, Map.class);
			for (Map map : mapList) {
				CostWorkOrderStatus workOrderStatus = new CostWorkOrderStatus();
				workOrderStatus.setWorkOrder(map.get("mo_no").toString());
				workOrderStatus.setCompleteTime(DateUtil.getDateTimeSlashFormat(map.get("mo_close_time").toString()));
				workOrderStatus.setMonth(DateUtil.getDateFormat(workOrderStatus.getCompleteTime()).substring(0,7));
				costWorkOrderStatusList.add(workOrderStatus);
			}
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}finally {
			try {
				in.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			httpUrlConnection.disconnect();
		}
		return costWorkOrderStatusList;
	}
}
